<template>
  <div class="outfit-detail">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 搭配详情内容 -->
    <div v-else-if="outfit" class="outfit-content">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="header-actions">
          <el-button @click="editOutfit" type="primary" plain>
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button @click="copyOutfit" type="success" plain>
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
          <el-button @click="shareOutfit" type="info" plain>
            <el-icon><Share /></el-icon>
            分享
          </el-button>
        </div>
      </div>

      <!-- 搭配基本信息 -->
      <el-card class="outfit-info-card">
        <div class="outfit-header">
          <div class="outfit-title">
            <h1>{{ outfit.name }}</h1>
            <div class="outfit-meta">
              <el-tag v-if="outfit.style" type="primary" size="small">{{ getStyleLabel(outfit.style) }}</el-tag>
              <el-tag v-if="outfit.season" type="success" size="small">{{ getSeasonLabel(outfit.season) }}</el-tag>
              <el-tag v-if="outfit.is_favorite" type="warning" size="small">
                <el-icon><Star /></el-icon>
                收藏
              </el-tag>
            </div>
          </div>
          <div class="outfit-actions">
            <el-button @click="toggleFavorite" :type="outfit.is_favorite ? 'warning' : 'default'" circle>
              <el-icon><Star /></el-icon>
            </el-button>
            <el-button @click="wearToday" type="primary" circle>
              <el-icon><Check /></el-icon>
            </el-button>
          </div>
        </div>

        <div class="outfit-description" v-if="outfit.description">
          <p>{{ outfit.description }}</p>
        </div>

        <div class="outfit-stats">
          <div class="stat-item">
            <span class="stat-label">评分</span>
            <el-rate
              v-model="outfit.rating"
              :max="5"
              show-score
              @change="updateRating"
              text-color="#ff9900"
            />
          </div>
          <div class="stat-item">
            <span class="stat-label">穿着次数</span>
            <span class="stat-value">{{ outfit.wear_count || 0 }} 次</span>
          </div>
          <div class="stat-item" v-if="outfit.last_worn_date">
            <span class="stat-label">最后穿着</span>
            <span class="stat-value">{{ formatDate(outfit.last_worn_date) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 搭配单品展示 -->
      <el-card class="outfit-items-card">
        <template #header>
          <div class="card-header">
            <span>搭配单品 ({{ outfit.clothes?.length || 0 }}件)</span>
            <el-button @click="manageItems" type="primary" size="small" plain>
              <el-icon><Setting /></el-icon>
              管理单品
            </el-button>
          </div>
        </template>

        <div v-if="outfit.clothes && outfit.clothes.length > 0" class="items-grid">
          <div
            v-for="item in outfit.clothes"
            :key="item.id"
            class="item-card"
            @click="viewClothingDetail(item.id)"
          >
            <div class="item-image">
              <el-image
                :src="item.main_image || '/placeholder-clothing.png'"
                :alt="item.name"
                fit="cover"
                class="clothing-image"
              />
              <div class="item-overlay">
                <el-button type="primary" circle size="small">
                  <el-icon><View /></el-icon>
                </el-button>
              </div>
            </div>
            <div class="item-info">
              <h4 class="item-name">{{ item.name }}</h4>
              <p class="item-details">{{ item.color }} | {{ item.category?.name }}</p>
              <div class="item-meta">
                <el-tag size="small" type="info">{{ item.brand || '无品牌' }}</el-tag>
                <span class="item-price" v-if="item.price">¥{{ item.price }}</span>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="no-items">
          <el-empty description="暂无搭配单品">
            <el-button @click="addItems" type="primary">添加单品</el-button>
          </el-empty>
        </div>
      </el-card>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-result
        icon="warning"
        title="搭配不存在"
        sub-title="您访问的搭配可能已被删除或不存在"
      >
        <template #extra>
          <el-button @click="goBack" type="primary">返回</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { outfitAPI } from '@/api'

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const outfit = ref(null)

// 计算属性
const outfitId = computed(() => route.params.id)

// 方法
const loadOutfitDetail = async () => {
  loading.value = true
  try {
    const response = await outfitAPI.getDetail(outfitId.value)
    outfit.value = response.data
  } catch (error) {
    console.error('加载搭配详情失败:', error)
    ElMessage.error('加载搭配详情失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

const editOutfit = () => {
  router.push(`/outfits/${outfitId.value}/edit`)
}

const copyOutfit = async () => {
  try {
    await outfitAPI.copy(outfitId.value)
    ElMessage.success('搭配已复制')
  } catch (error) {
    console.error('复制搭配失败:', error)
    ElMessage.error('复制失败，请稍后重试')
  }
}

const shareOutfit = () => {
  // TODO: 实现分享功能
  ElMessage.info('分享功能开发中...')
}

const toggleFavorite = async () => {
  try {
    await outfitAPI.toggleFavorite(outfitId.value)
    outfit.value.is_favorite = !outfit.value.is_favorite
    ElMessage.success(outfit.value.is_favorite ? '已收藏' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const wearToday = async () => {
  try {
    await ElMessageBox.confirm('确定要记录今天穿这套搭配吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await outfitAPI.wearToday(outfitId.value)
    ElMessage.success('已记录今日穿搭')

    // 重新加载数据以更新穿着次数
    await loadOutfitDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('记录穿搭失败:', error)
      ElMessage.error('记录失败，请稍后重试')
    }
  }
}

const updateRating = async (rating) => {
  try {
    await outfitAPI.rate(outfitId.value, rating)
    ElMessage.success('评分已更新')
  } catch (error) {
    console.error('更新评分失败:', error)
    ElMessage.error('评分失败，请稍后重试')
    // 恢复原评分
    await loadOutfitDetail()
  }
}

const viewClothingDetail = (clothingId) => {
  router.push(`/wardrobe/${clothingId}`)
}

const manageItems = () => {
  router.push(`/outfits/${outfitId.value}/edit`)
}

const addItems = () => {
  router.push(`/outfits/${outfitId.value}/edit`)
}

// 工具函数
const getStyleLabel = (style) => {
  const styleMap = {
    casual: '休闲',
    formal: '正式',
    business: '商务',
    sport: '运动',
    party: '派对',
    vintage: '复古',
    street: '街头'
  }
  return styleMap[style] || style
}

const getSeasonLabel = (season) => {
  const seasonMap = {
    spring: '春季',
    summer: '夏季',
    autumn: '秋季',
    winter: '冬季',
    all: '四季'
  }
  return seasonMap[season] || season
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadOutfitDetail()
})
</script>

<style scoped>
.outfit-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading-container {
  padding: 40px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.outfit-info-card {
  margin-bottom: 20px;
}

.outfit-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.outfit-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.outfit-meta {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.outfit-actions {
  display: flex;
  gap: 8px;
}

.outfit-description {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  color: #606266;
  line-height: 1.6;
}

.outfit-stats {
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.outfit-items-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.item-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
}

.item-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.item-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.clothing-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.item-card:hover .item-overlay {
  opacity: 1;
}

.item-info {
  padding: 16px;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-details {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 14px;
  font-weight: 500;
  color: #f56c6c;
}

.no-items {
  text-align: center;
  padding: 40px;
}

.error-container {
  padding: 40px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .outfit-detail {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .outfit-header {
    flex-direction: column;
    gap: 16px;
  }

  .outfit-stats {
    gap: 16px;
  }

  .items-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 16px;
  }

  .item-image {
    height: 150px;
  }
}
</style>
